import type {
  PowerDistributionFacilitiesOptionsPropsType,
  PowerDistributionFacilitiesOptionsStateType
} from './typings'
import { defineComponent, ref, reactive, onMounted } from 'vue'
import { useStore } from 'vuex'
import dayjs from 'dayjs'
import { values } from 'lodash'
import {
  // ElDialog,
  ElCard,
  // ElLink,
  ElDivider,
  ElTabs,
  ElTabPane,
  ElSkeleton,
  ElSpace,
  ElButton,
  ElLoading,
  ElMessage,
  ElMessageBox,
  ElRow,
  ElCol
} from 'element-plus'
import AliIcon from '~/components/AliIocn'
import SaasTitle from '~/components/SaasTitle'
import BasicInformation from '../../components/powerDistributionFacilitiesComponents/BasicInformation'
import MapLocation from '../../components/powerDistributionFacilitiesComponents/MapLocation'
import LoopInformation from '../../components/powerDistributionFacilitiesComponents/LoopInformation'
import AssociatedFacilities from '../../components/powerDistributionFacilitiesComponents/AssociatedFacilities'
import { handleTrim } from '~/utils/util'
import { GUTTER, SPAN_STYLE_TWO_THIRD, SPAN_STYLE_ONE_THIRD } from '~/utils/const'
import styles from '../../index.module.scss'

export default defineComponent({
  name: 'PowerDistributionFacilitiesOptions',
  props: ['record', 'type', 'changeType', 'cancel'],
  setup(props: PowerDistributionFacilitiesOptionsPropsType) {
    const store = useStore()
    const infoRef = ref()
    const mapLocationRef = ref()
    const loopInformationRef = ref()
    const state = reactive<PowerDistributionFacilitiesOptionsStateType>({
      activeTabKey: 'info',
      detail: {},
      loading: false
    })
    const title = { add: '新增', update: '编辑', read: '查看' }

    // 基础资料form提交
    const handleSubmitBaseInfoForm = () => {
      infoRef.value.ruleFormRef.validate((valid: boolean) => {
        mapLocationRef.value.ruleFormRef.validate(async (valid2: boolean) => {
          if (!valid || !valid2) return
          state.loading = true
          const params = {
            ...(infoRef.value.formValues || {}),
            ...(mapLocationRef.value.formValues || {})
          }
          params.name = handleTrim(params.name)
          params.tenKv = params.tenKv && handleTrim(params.tenKv)
          params.highNo = params.highNo && handleTrim(params.highNo)
          params.capacity = params.capacity && handleTrim(params.capacity)
          params.deliverDate = params.deliverDate ? dayjs(params.deliverDate).format() : undefined
          params.memo = params.memo && handleTrim(params.memo)
          // params.isDeliver = params.isDeliver ? 1 : 0
          params.imageUrl = params.imageUrl?.length ? params.imageUrl.join(',') : ''
          params.addressCoordinates =
            params.addressCoordinates && handleTrim(params.addressCoordinates)
          if (params.addressCoordinates) {
            params.lon = params.addressCoordinates.split(',')?.[0] || undefined
            params.lat = params.addressCoordinates.split(',')?.[1] || undefined
            params.addressCoordinates = undefined
          }

          const res = await store.dispatch(
            props.type === 'add'
              ? 'powerDistributionFacilities/AddPowerDistributionFacilitiesInfo'
              : 'powerDistributionFacilities/UpdatePowerDistributionFacilitiesInfo',
            params
          )
          if (res?.code === 200) {
            ElMessage({ type: 'success', message: '操作成功' })

            props.changeType('update', res?.data, true)
            // props.cancel()
            // 保存成功则重新查询最新的详情
            // handleGetBasicInfoById()
            // 保存成功则重新设置最新的详情
            state.detail = res?.data
          }
          state.loading = false
        })
      })
    }

    // 地图位置form提交
    /* const handleSubmitMapLoactionForm = () => {
      mapLocationRef.value.ruleFormRef.validate(async (valid: boolean) => {
        if (!valid) return
        state.loading = true
        const params = { ...mapLocationRef.value.formValues }
        params.addressCoordinates =
          params.addressCoordinates && handleTrim(params.addressCoordinates)
        if (params.addressCoordinates) {
          params.lon = params.addressCoordinates.split(',')?.[0] || undefined
          params.lat = params.addressCoordinates.split(',')?.[1] || undefined
          params.addressCoordinates = undefined
        }
        const res = await store.dispatch(
          'powerDistributionFacilities/UpdatePowerDistributionFacilitiesMapLocation',
          params
        )
        if (res?.code === 200) {
          ElMessage({ type: 'success', message: '操作成功' })
          props.cancel()
        }
        state.loading = false
      })
    } */

    // 回路信息form信息保存
    const handleSubmitSaveLoopInformation = async (loopList: Record<string, any>[]) => {
      state.loading = true
      const params = {
        distributionId: props.record.id,
        loopVersion: state.detail?.loopVersion,
        deleteLoopIds: loopInformationRef.value.deleteLoopIds?.join?.(',') || '',
        assetDistributionLoopList: loopList?.map((item) => ({
          ...item,
          lampPostIds: item.lampPostIds?.join?.(',') || '',
          // phase: item.phase || '',
          phase: item.phase ? JSON.stringify(item.phase) : '',
          distributionId: props.record.id,
          distributionName: props.record.name
        }))
      }
      const res = await store.dispatch(
        'powerDistributionFacilities/SavePowerDistributionFacilitiesLoop',
        params
      )
      if (res?.code === 200) {
        ElMessage({ type: 'success', message: '操作成功' })
        handleGetBasicInfoById()
        // props.cancel()
      }
      state.loading = false
    }

    // 回路信息form提交
    const handleSubmitLoopInformation = () => {
      const loopList = values(loopInformationRef.value.formValues || [])
      if (!loopList?.length) {
        ElMessage.error('请设置回路')
        return
      }
      loopInformationRef.value.verifyActiveLoopType()
      loopInformationRef.value.ruleFormRef.validate(async (valid: boolean) => {
        if (!valid) return
        const res = await store.dispatch('loopMonitoringBox/GetDistributionCheckLoopVersion', {
          id: props.record.id,
          loopVersion: state.detail?.loopVersion
        })

        if (res?.data) {
          if (res?.data?.isUpdate) {
            ElMessageBox({
              title: '提示',
              message: res?.data?.msg,
              showClose: false,
              showCancelButton: true,
              confirmButtonText: '覆盖',
              cancelButtonText: '刷新',
              closeOnClickModal: false, // 点遮罩层不关弹窗
              draggable: true // 可拖拽
            })
              .then(() => {
                handleSubmitSaveLoopInformation(loopList)
              })
              .catch(handleGetBasicInfoById)
            // .catch(() => {
            //   location.reload()
            // })
          } else {
            handleSubmitSaveLoopInformation(loopList)
          }
        }
      })
    }

    // 提交表单  根据activetabkey 来判断使用哪个方法
    const handleSubmitForm = () => {
      // 基础资料保存
      if (state.activeTabKey === 'info') {
        handleSubmitBaseInfoForm()
      }
      // 地图位置保存
      // if (state.activeTabKey === 'mapLocation') {
      //   handleSubmitMapLoactionForm()
      // }
      // 回路信息保存
      if (state.activeTabKey === 'loopInformation') {
        handleSubmitLoopInformation()
      }
    }

    // 获取详情数据
    const handleGetBasicInfoById = async () => {
      const loading = ElLoading.service({
        target: '.el-dialog'
      })
      const result = await store.dispatch(
        'powerDistributionFacilities/GetPowerDistributionFacilitiesInfo',
        { id: props.record?.id }
      )

      state.detail = result?.data
      loading.close()
    }

    onMounted(() => {
      // 获取回路信息中的颜色列表
      store.dispatch('loopMonitoringBox/GetLoopConfigureColors')
      if (props?.record?.id) handleGetBasicInfoById()
    })

    return () => {
      const { type, cancel } = props
      return (
        <ElCard
          class={{
            'covered-with-info-content': true,
            'covered-with-info-has-option-btn':
              type !== 'read' &&
              (state.activeTabKey === 'info' || state.activeTabKey === 'loopInformation'),
            [styles['info-card-box']]: true
          }}
          v-slots={{
            header: () => (
              <ElSpace class="info-card-header-space">
                <SaasTitle type="primary">{(title[type] as string) || '查看'}配电设施</SaasTitle>
                <ElButton link type="primary" onClick={props.cancel}>
                  返回上一级&nbsp;
                  <AliIcon type="icon-fanhuishangyiji" />
                </ElButton>
              </ElSpace>
            )
          }}
        >
          <ElTabs
            v-model={state.activeTabKey}
            // type="border-card"
            class={{
              [styles['power-distribution-facilities-tabs']]: true,
              'covered-with-tabs': true
            }}
          >
            <ElTabPane name="info" label="基础资料">
              {type === 'add' || state.detail?.id ? (
                <ElRow gutter={GUTTER} class={styles['info-content-height-full-box']}>
                  <ElCol {...SPAN_STYLE_ONE_THIRD}>
                    <BasicInformation ref={infoRef} detail={state.detail} type={props.type} />
                  </ElCol>
                  <ElCol {...SPAN_STYLE_TWO_THIRD} class={styles['map-location']}>
                    <MapLocation ref={mapLocationRef} detail={state.detail} />
                  </ElCol>
                </ElRow>
              ) : (
                <ElSkeleton rows={5} animated />
              )}
            </ElTabPane>
            {/* <ElTabPane name="mapLocation" label="地图位置" disabled={type === 'add'} lazy>
              <MapLocation ref={mapLocationRef} detail={state.detail} />
            </ElTabPane> */}
            <ElTabPane
              name="loopInformation"
              label="回路信息"
              disabled={type === 'add' || (!state.detail?.lon && !state.detail?.lat)}
              lazy
            >
              <LoopInformation ref={loopInformationRef} detail={state.detail} />
            </ElTabPane>
            <ElTabPane name="associatedFacilities" label="关联设施" disabled={type === 'add'} lazy>
              <AssociatedFacilities detail={state.detail} />
            </ElTabPane>
            {/* <ElTabPane name="operationRecord" label="操作记录" disabled={type === 'add'} lazy>
              操作记录
            </ElTabPane> */}
          </ElTabs>
          {type !== 'read' &&
            (state.activeTabKey === 'info' || state.activeTabKey === 'loopInformation') && (
              <section class="fixed-option-btns">
                <ElDivider />
                <ElSpace class="form-options-btns">
                  <ElButton plain onClick={cancel}>
                    取消
                  </ElButton>
                  <ElButton type="primary" onClick={handleSubmitForm} loading={state.loading}>
                    保存
                  </ElButton>
                </ElSpace>
              </section>
            )}
        </ElCard>
      )
    }
  }
})
